import { useEffect, useCallback } from 'react';
import {useDispatchCurDevice} from "../stores/hooks/index.ts";

const WIDTH = 768; // 与 Bootstrap 的 md 断点对齐

export function useDevice() {
  const {setCurDeviceState}=useDispatchCurDevice()
  // 判断当前屏幕是否为移动端
  const isMobile = useCallback(() => {
    return document.body.getBoundingClientRect().width - 1 < WIDTH;
  }, []);

  // 响应式处理函数
  const resizeHandler = useCallback(() => {
    if (!document.hidden) {
      const isMobileDevice = isMobile();
      const curDevice = isMobileDevice ? 'mobile' : 'desktop';
      setCurDeviceState(curDevice);
    }
  }, [isMobile]);

  // 初始化设备状态
  useEffect(() => {
    window.addEventListener('resize', resizeHandler);
    return () => {
      window.removeEventListener('resize', resizeHandler);
    };
  }, [resizeHandler]);
  return { isMobile };
}